package com.zwg.git_customview.mp4

// MediaPlayerHelper.kt
import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.zwg.git_customview.R
import java.io.IOException

class MediaPlayerHelper(private val context: Context, private val surfaceView: SurfaceView) :
    SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

    private var mediaPlayer: MediaPlayer? = null

    init {
        surfaceView.holder.addCallback(this)
    }

    fun playVideo() {
        try {
            mediaPlayer = MediaPlayer().apply {
                setDataSource(context, Uri.parse("android.resource://${context.packageName}/${R.raw.login_bg}"))
                setDisplay(surfaceView.holder)
                setOnPreparedListener(this@MediaPlayerHelper)
                setOnErrorListener(this@MediaPlayerHelper)
                prepareAsync()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        // Do nothing
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // Do nothing
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        mediaPlayer?.release()
        mediaPlayer = null
    }

    override fun onPrepared(mp: MediaPlayer) {
        mp.start()
    }

    override fun onError(mp: MediaPlayer, what: Int, extra: Int): Boolean {
        // Handle error
        mp.reset()
        return true
    }
}
